<?php

namespace Fang\CouponBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Fang\CouponBundle\Form\User\UserRegister;
use Fang\CouponBundle\Entity\User;
use Symfony\Component\Form\FormError;

class IndexController extends Controller
{
  /**
  * 使用
  * @Route("/coupon/{page}", name="couponindex", requirements={"page":"\d+"})
  **/
  public function indexAction($page=2)
  {
  	$url = $this->generateUrl("couponindex", array("page"=>$page+1, "_cn"=>time()));
    // return new Response('<html><body>Lucky number: test'.$page.'<a href="'.$url.'">testurl</a></body></html>');
    //return $this->json(array("page"=>$page+1));
    return $this->render("@FangCoupon/index/index.html.twig");
  }
  /**
  *表单测试
  * @Route("/coupon/form", name="couponform")
  **/
  public function formAction(Request $request)
  {
    //创建表单
    $user = new User();
    $form = $this->createForm(UserRegister::class, $user);
    //处理表单，将提交信息放入到对象中
    $form->handleRequest($request);
    if($form->isSubmitted() && $form->isValid())
    {
      $user = $form->getData();
      //查询用户名是否已经存在
      $findUser = $this->getDoctrine()->getRepository("FangCouponBundle:User")->findOneByUsername($user->getUsername());
      if(!$findUser)
      {
        $user->setActive(true);
        $user->setCreated(time());
        $user->setChanged($user->getCreated());
        //获取数据库的操作对象
        $em = $this->getDoctrine()->getManager();
        //存入要保存对象
        $em->persist($user);
        //真正执行保存数据
        $em->flush();
      }
      $form->addError(new FormError("username had exists"));
      dump($user);
    }

    return $this->render("@FangCoupon/index/register.html.twig", array("registerForm"=>$form->createView(),));
  }
}